<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="商家名称" prop="merchantName">
        <el-input
          v-model="queryParams.merchantName"
          placeholder="请输入商家名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="联系人" prop="contactPerson">
        <el-input
          v-model="queryParams.contactPerson"
          placeholder="请输入联系人"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="联系电话" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入联系电话"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
     
     
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择状态"
          clearable
          class="!w-240px"
        >

              <el-option
                  v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
              />

        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['juliang:merchant:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['juliang:merchant:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="主键ID" align="center" prop="id" />
      <el-table-column label="商家名称" align="center" prop="merchantName" />
      <el-table-column label="联系人" align="center" prop="contactPerson" />
      <el-table-column label="联系电话" align="center" prop="phone" />
      <el-table-column label="授信类型" align="center" prop="creditType">
        <template #default="scope">
          <dict-tag v-if="scope.row.creditType !== null" :type="DICT_TYPE.JULIANG_CREDIT_TYPE" :value="scope.row.creditType" />
          <span v-else>暂无授信</span>
        </template>
      </el-table-column>
      <el-table-column label="授信额度" align="center" prop="creditAmount">
        <template #default="scope">
          {{ scope.row.creditType === 1 ? scope.row.creditAmount : '--' }}
        </template>
      </el-table-column>
      <el-table-column label="授信比例" align="center" prop="creditRatio">
        <template #default="scope">
          {{ scope.row.creditType === 2 ? scope.row.creditRatio + '%' : '--' }}
        </template>
      </el-table-column>
      <el-table-column label="授信状态" align="center" prop="creditStatus">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.COMMON_STATUS" :value="scope.row.creditStatus" />
        </template>
      </el-table-column>
     
      <el-table-column label="备款余额" align="center" prop="balance" width="150px">
        <template #default="scope">
          <div>
            <span :class="{ 'negative-balance': (scope.row.balance || 0) < 0 }">
              {{ scope.row.balance || 0 }}元
            </span>
          </div>
          <div class="mt-1">
            <el-button 
              link 
              type="primary" 
              size="small"
              @click="openTransferRecordDialog(scope.row)"
            >
             转账记录
            </el-button>
            <el-button 
              link 
              type="warning" 
              size="small"
              @click="openNotifyMessageDialog(scope.row)"
            >
              催收消息
            </el-button>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="冻结金额" align="center" prop="frozenAmount" width="120px"/>
      <el-table-column label="电子邮箱" align="center" prop="email"  width="100px"/>
      <el-table-column label="地址" align="center" prop="address" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />

      <el-table-column label="操作" align="center" min-width="350px" fixed="right">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['juliang:merchant:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="warning"
            @click="openDunningDialog(scope.row)"
            v-hasPermi="['juliang:merchant:update']"
          >
            发送催款
          </el-button>
          <el-button
            v-if="(scope.row.balance || 0) > 0"
            link
            type="info"
            @click="openTransferDialog(scope.row)"
            v-hasPermi="['juliang:merchant:update']"
          >
            转账
          </el-button>
          <el-button
            link
            :type="scope.row.status === 0 ? 'danger' : 'success'"
            @click="handleBanAccount(scope.row)"
            v-hasPermi="['juliang:merchant:update']"
          >
            {{ scope.row.status === 0 ? '封禁账号' : '解封账号' }}
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['juliang:merchant:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <MerchantForm ref="formRef" @success="getList" />
  
  <!-- 转账表单 -->
  <TransferForm v-model="transferDialogVisible" @success="getList" ref="transferFormRef" />
  
  <!-- 转账记录弹窗 -->
  <TransferRecordDialog v-model="transferRecordDialogVisible" ref="transferRecordDialogRef" />
  
  <!-- 催收消息弹窗 -->
  <Dialog :title="'催收消息记录'" v-model="notifyMessageDialogVisible" width="1000px">
    <el-table v-loading="notifyMessageLoading" :data="notifyMessageList" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="消息标题" align="center" prop="templateNickname" width="150px" />
      <el-table-column label="消息内容" align="center" prop="templateContent" min-width="300px" />
      <el-table-column label="发送时间" align="center" prop="createTime" width="180px">
        <template #default="scope">
          {{ formatDate(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="消息状态" align="center" prop="readStatus" width="100px">
        <template #default="scope">
          <el-tag :type="scope.row.readStatus ? 'success' : 'info'">
            {{ scope.row.readStatus ? '已读' : '未读' }}
          </el-tag>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 催收消息分页 -->
    <div class="pagination-wrapper">
      <Pagination
        :total="notifyMessageTotal"
        v-model:page="notifyMessageParams.pageNo"
        v-model:limit="notifyMessageParams.pageSize"
        @pagination="getNotifyMessageList"
      />
    </div>
  </Dialog>

  <!-- 催款弹窗 -->
  <Dialog :title="'发送催款通知'" v-model="dunningDialogVisible" width="600px">
    <el-form
      ref="dunningFormRef"
      :model="dunningForm"
      :rules="dunningRules"
      label-width="120px"
    >
      <el-form-item label="商家信息">
        <el-input
          :value="`商家: ${currentMerchant?.merchantName || ''} (余额: ${currentMerchant?.balance || 0}元)`"
          disabled
        />
      </el-form-item>
      <el-form-item label="催款内容" prop="content">
        <el-input
          v-model="dunningForm.content"
          type="textarea"
          :rows="4"
          placeholder="请输入催款内容"
          maxlength="500"
          show-word-limit
        />
      </el-form-item>
      <el-form-item label="备注">
        <div style="font-size: 14px; color: #909399;">
          系统将通过站内消息向商家发送催款通知。
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dunningDialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="handleSendDunning" :loading="dunningLoading">发送催款</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { getIntDictOptions, getStrDictOptions, getBoolDictOptions, DICT_TYPE } from '@/utils/dict'
import { CommonStatusEnum } from '@/utils/constants'
import { dateFormatter, formatDate } from '@/utils/formatTime'
import download from '@/utils/download'
import { MerchantApi, MerchantVO } from '@/api/juliang/merchant'
import MerchantForm from './MerchantForm.vue'
import TransferForm from './TransferForm.vue'
import TransferRecordDialog from './TransferRecordDialog.vue'
import request from '@/config/axios'

import { createImageViewer } from '@/components/ImageViewer'


/** 商品图预览 */
const imagePreview = (imgUrl: string) => {
  createImageViewer({
    urlList: [imgUrl]
  })
}

    
/** 商家信息 列表 */
defineOptions({ name: 'Merchant' })

const message = useMessage() // 消息弹窗

const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<MerchantVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  merchantName: undefined,
  contactPerson: undefined,
  phone: undefined,
  email: undefined,
  address: undefined,
  createTime: [],
  status: undefined,
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await MerchantApi.getMerchantPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await MerchantApi.deleteMerchantById(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await MerchantApi.exportMerchant(queryParams)
    download.excel(data, '商家信息.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 催款相关 */
const dunningDialogVisible = ref(false)
const dunningLoading = ref(false)
const dunningFormRef = ref()
const currentMerchant = ref<MerchantVO | null>(null)
const dunningForm = reactive({
  merchantId: undefined as number | undefined,
  content: ''
})

const dunningRules = reactive({
  content: [{ required: true, message: '请输入催款内容', trigger: 'blur' }]
})

/** 转账相关 */
const transferDialogVisible = ref(false)
const transferFormRef = ref()

/** 转账记录相关 */
const transferRecordDialogVisible = ref(false)
const transferRecordDialogRef = ref()

/** 催收消息相关 */
const notifyMessageDialogVisible = ref(false)
const notifyMessageLoading = ref(false)
const notifyMessageList = ref([])
const notifyMessageTotal = ref(0)
const notifyMessageParams = reactive({
  pageNo: 1,
  pageSize: 10,
  merchantId: undefined as number | undefined
})



/** 打开催款弹窗 */
const openDunningDialog = (row: MerchantVO) => {
  currentMerchant.value = row
  dunningForm.merchantId = row.id
  dunningForm.content = `尊敬的商家，您的账户余额为${row.balance || 0}元，余额不足。请及时充值以确保业务正常运行。如有疑问，请联系客服。`
  dunningDialogVisible.value = true
}

/** 处理发送催款 */
const handleSendDunning = async () => {
  try {
    // 校验表单
    if (!dunningFormRef.value) {
      message.error('表单未初始化，请重新打开催款弹窗')
      return
    }
    await dunningFormRef.value.validate()
    
    dunningLoading.value = true
    
    // 构造催款数据
    const dunningData = {
      merchantId: dunningForm.merchantId!,
      money: Math.abs(currentMerchant.value?.balance || 0)
    }
    
    // 调用催款API
    await MerchantApi.sendDunningNotice(dunningData)
    
    message.success('催款通知发送成功')
    dunningDialogVisible.value = false
    
    // 刷新列表
    await getList()
  } catch (error) {
    console.error('发送催款失败:', error)
    message.error('发送催款失败，请重试')
  } finally {
    dunningLoading.value = false
  }
}

/** 处理封禁/解封账号 */
const handleBanAccount = async (row: MerchantVO) => {
  try {
    const isCurrentlyActive = row.status === 0
    const action = isCurrentlyActive ? '封禁' : '解封'
    const newStatus = isCurrentlyActive ? 1 : 0
    
    // 封禁/解封的二次确认
    await message.confirm(`确认要${action}商家"${row.merchantName}"的账号吗？${isCurrentlyActive ? '封禁后该商家将无法正常使用系统功能。' : ''}`)
    
    // 发起封禁/解封请求
    await MerchantApi.updateMerchantStatus(row.id, newStatus)
    
    message.success(`${action}成功`)
    
    // 刷新列表
    await getList()
  } catch (error) {
    console.error('操作失败:', error)
  }
}

/** 打开转账弹窗 */
const openTransferDialog = (row: MerchantVO) => {
  if (!transferFormRef.value) {
    message.error('转账组件未初始化，请刷新页面重试')
    return
  }
  
  try {
    transferFormRef.value.open(row)
  } catch (error) {
    console.error('打开转账弹窗失败:', error)
    message.error('打开转账弹窗失败，请重试')
  }
}

/** 打开转账记录弹窗 */
const openTransferRecordDialog = (row: MerchantVO) => {
  if (!transferRecordDialogRef.value) {
    message.error('转账记录组件未初始化，请刷新页面重试')
    return
  }
  
  try {
    transferRecordDialogRef.value.open({
      id: row.id,
      merchantName: row.merchantName
    })
  } catch (error) {
    console.error('打开转账记录弹窗失败:', error)
    message.error('打开转账记录弹窗失败，请重试')
  }
}

/** 获取催收消息列表 */
const getNotifyMessageList = async () => {
  notifyMessageLoading.value = true
  try {
    const data = await request.get({
      url: '/system/notify-message/page',
      params: {
        pageNo: notifyMessageParams.pageNo,
        pageSize: notifyMessageParams.pageSize,
        merchantId: notifyMessageParams.merchantId
      }
    })
    notifyMessageList.value = data.list || []
    notifyMessageTotal.value = data.total || 0
  } catch (error) {
    console.error('获取催收消息失败:', error)
    message.error('获取催收消息失败，请重试')
    notifyMessageList.value = []
    notifyMessageTotal.value = 0
  } finally {
    notifyMessageLoading.value = false
  }
}

/** 打开催收消息弹窗 */
const openNotifyMessageDialog = (row: MerchantVO) => {
  notifyMessageParams.merchantId = row.id
  notifyMessageParams.pageNo = 1
  notifyMessageDialogVisible.value = true
  nextTick(() => {
    getNotifyMessageList()
  })
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
// 负余额样式
.negative-balance {
  font-weight: bold;
  color: #f56c6c;
}

.mt-1 {
  margin-top: 4px;
}

.pagination-wrapper {
  display: flex;
  margin-top: 16px;
  justify-content: center;
  align-items: center;
}
</style>